import { IAppDEUIAction } from '@ibiz/model-core';
import {
  IUIActionResult,
  IUILogicParams,
  FrontUIActionProvider,
  GridController,
} from '@ibiz-template/runtime';

/**
 * 保存查询列表行为适配器
 *
 * @export
 * @class SaveSearchListUIActionProvider
 * @extends {FrontUIActionProvider}
 */
export class SaveSearchListUIActionProvider extends FrontUIActionProvider {
  async execAction(
    action: IAppDEUIAction,
    args: IUILogicParams,
  ): Promise<IUIActionResult> {
    const actionResult: IUIActionResult = {};
    const data = args.data[0];
    const entityIds: string[] = Object.keys(data);
    if (entityIds.length > 0) {
      const saveDataPromises = entityIds.map(entityId =>
        this.saveData(entityId, data[entityId], args.context),
      );
      await Promise.all(saveDataPromises);
    }
    await this.refreshGrid(args.view, entityIds);
    return actionResult;
  }

  /**
   * 保存数据
   *
   * @private
   * @param {string} entityId
   * @param {IData[]} items
   * @param {IContext} context
   * @return {*}  {Promise<void>}
   * @memberof SaveSearchListUIActionProvider
   */
  private async saveData(
    entityId: string,
    items: IData[],
    context: IContext,
  ): Promise<void> {
    const app = ibiz.hub.getApp(context.srfappid);
    const promises = items.map(item =>
      app.deService.exec(entityId, 'create', context, item),
    );
    await Promise.all(promises);
  }

  /**
   * 刷新指定表格
   *
   * @private
   * @param {IData} view 视图控制器
   * @param {string[]} entityIds 标识集合
   * @memberof SaveSearchListUIActionProvider
   */
  private async refreshGrid(view: IData, entityIds: string[]): Promise<void> {
    const promises = entityIds.map((key: string) => {
      const mdCtrlGrid: GridController = view.ctx.controllersMap.get(
        `${key}_grid`,
      );
      return mdCtrlGrid?.refresh();
    });
    await Promise.all(promises);
  }
}
